define(function (require, exports, module) {

	require("./AnnotSelectionTool.js");
	require("./AnnotHandleManager.js");
    var CPDF_Annot = FXREADER.PDFData.CPDF_Annot;
    var CAnnotFactory = FXREADER.CAnnotFactory;
    var CAnnot_PageEventHandler = require('./AnnotPageEvent');
    var CAnnot_MousePtHandler = require('./AnnotMousePtHandler');
    var CAnnot_DocViewEventHandler = require('./AnnotDocViewEventHandler');
    var CommonTools = FXREADER.Common;
    require("./CommentsAnnot.js");
    var AnnotDataJsonFmt =
    {
        PageIndex: "number",
        Annots: "annots"
    };

	FXREADER.BASEANNOT_PLUGIN_NAME	= "BaseAnnotPlugin";
	
	FXREADER.CBaseAnnotPlugin = function (pReaderApp) {
        var _pReaderApp = pReaderApp,
        	_pAnnotHandlerMgr = null,
        	 //是否初始化完成;
            _bInited = false,
        	_self = this;
        // 存储已经创建html的页面索引 ，格式为 :   页面索引：true/fase;
        var _PageAnnotCreatedList = {};
        var _PageAnnotUpdatedList = [];
        
        //private methods
        function _Init(jsonAnnotData) {
           
            var pPDFDoc = pReaderApp.GetPDFDoc();
            for (var i = 0; i < jsonAnnotData.length; i++) {
                var iPageNum = jsonAnnotData[i][AnnotDataJsonFmt.PageIndex];
                var pPDFPage = pPDFDoc.GetPage(iPageNum);
                var jsonAnnots = jsonAnnotData[i][AnnotDataJsonFmt.Annots];
                for (var j = 0; j < jsonAnnots.length; j++) {
                    var pAnnot = CAnnotFactory.CreateAnnot(jsonAnnots[j]);
                    pPDFPage.AddAnnot(pAnnot);
                    _AddGourpAnnot2Page(pAnnot, pPDFPage);
                }
            }
            _bInited = true;

            
            _pAnnotHandlerMgr.Init();
            var pDocView = _pReaderApp.GetMainView().GetDocView();
            var visablePageRange = pDocView.GetDisplayPageRange();
            var jqPagesContainerDiv = $("#" + pDocView.GetDocViewContainerID());
            var contentPaneHeight = jqPagesContainerDiv.height();
            var contentPanelWidth = jqPagesContainerDiv.width();
            var contentPanelOffset = jqPagesContainerDiv.offset();
            for (var i = visablePageRange.begin; i <= visablePageRange.end; i++) {
                _self.OnPageVisable(pReaderApp.GetMainView().GetDocView().GetPageView(i), contentPanelWidth, contentPaneHeight, contentPanelOffset);
            }
        }

        function _AddGourpAnnot2Page(annot, pPDFPage) {
            if (pPDFPage && annot && annot.GetType() == "Markup") {
                var nGroupAnnotCnt = annot.CountGroupAnnots();
                for (var k = 0; k < nGroupAnnotCnt; k++) {
                    var pGroupAnnot = annot.GetAnnotFromGroup(k);
                    pPDFPage.AddAnnot(pGroupAnnot);
                    _AddGourpAnnot2Page(pGroupAnnot, pPDFPage);
                }
            }
        }

    

        
        this.GetPluginName = function () {
            return FXREADER.BASEANNOT_PLUGIN_NAME;
        };
        
        
        //模块初始化;
        this.PIInit = function () {
        	_pAnnotHandlerMgr = new FXREADER.AnnotHandleManager(_pReaderApp);
        	var pAnnotSelectionTool = new FXREADER.Event.AnnotSelectionToolHandler(_pReaderApp,_pAnnotHandlerMgr);
        	_pReaderApp.RegisterToolHandler(pAnnotSelectionTool);
        	
        	var pAnnotPageEventHandler = new CAnnot_PageEventHandler(_self);
            var pAnnotMousePtHandler = new CAnnot_MousePtHandler(_self);
            _pReaderApp.RegisterPageEventHandler(pAnnotPageEventHandler);
            _pReaderApp.RegisterMousePtHandler(pAnnotMousePtHandler);
            var pAnnotDocViewEventHandler = new CAnnot_DocViewEventHandler(_self);
            _pReaderApp.RegisterDocViewEventHandler(pAnnotDocViewEventHandler);
            _self.ResetAnnotUpdatedList();
            _self.GetAnnotData(FXREADER.Config.requestRetryCount);
        };

        //从网络上获取Annot数据;
        this.GetAnnotData = function (retryCount) {
        	 if (retryCount <= 0) {
                 throw new Error('Maximum number of retries exceeded for GetAnnotData request.');
             }
            var data = { fileid: pReaderApp.GetFileID(), fname: pReaderApp.GetFileName() };
            $.ajax({
                url: FXREADER.Config.Url.GetAnnotData,
                type: 'POST',
                dataType: 'json',
                data: data,

                success: function (response) {
                    var error = response.error;
                    if (error != 0) {
                    	 if (FXREADER.Common.IsNeedRetry(response.status)) {
                    		 var interval = FXREADER.AjaxRetryManager.GetNextAnnotDataRequestInterval(_self.GetReaderApp().GetMainView().GetDocView().GetPageCount());
                             setTimeout(function () { _self.GetAnnotData(retryCount - 1); }, interval);
                             return;
                         }
                         else {
                             throw new Error('Get Annot Data Error:' + error);
                             return;
                         }
                    }
                    try {
                        var jsonAnnotData = $.parseJSON(response.AnnotData);
                        //初始化Annot;
                        if (jsonAnnotData != null) {
                            _pReaderApp.StepProgress();
                            _Init(jsonAnnotData);
                        }
                    }
                    catch (ex) {
                        throw ex;
                        return false;
                    }
                },
                error: function () {
                    throw new Error('Get Annot Data Error!');
                }
            });
        };

       
        //Doc View 消息响应；
        
        this.OnDocViewZoom = function (scale) {
        	
        };
        
        this.OnDocViewResize = function () {
            _self.ResetAnnotUpdatedList();
            var CanvasElem = _pAnnotHandlerMgr.GetCavansElement();
            var pDocView = _pReaderApp.GetMainView().GetDocView();
            var ScrollApi = pDocView.GetScrollApi();
            var jqPagesContainerDiv = $("#" + pDocView.GetDocViewContainerID());
            if (CanvasElem != null) {
                CanvasElem.width = jqPagesContainerDiv.width();
                CanvasElem.height = jqPagesContainerDiv.height();
                var fleft = 0, ftop = 0;
                if (ScrollApi) {
                    fleft = ScrollApi.getContentPositionX();
                    ftop = ScrollApi.getContentPositionY();
                }
                $(CanvasElem).css({ top: ftop, left: fleft });
            }
        };

        this.OnPreDocViewResize = function () {
            var CanvasElem = _pAnnotHandlerMgr.GetCavansElement();
            if (CanvasElem != null) {
                //在重新初始化滚动条时，忽略canvas高度;
                CanvasElem.height = 0;
                CanvasElem.width = 0;
                $(CanvasElem).css({ left: 0, top: 0 });
            }
        };


        this.OnDocViewScroll = function () {
            var pDocView = _pReaderApp.GetMainView().GetDocView();
            var ScrollApi = pDocView.GetScrollApi();
            var CanvasElem = _pAnnotHandlerMgr.GetCavansElement();
            if (CanvasElem != null) {
                var fleft = 0, ftop = 0;
                if (ScrollApi) {
                    fleft = ScrollApi.getContentPositionX();
                    ftop = ScrollApi.getContentPositionY();
                }

                $(CanvasElem).css({ top: ftop, left: fleft });
            }
            _pAnnotHandlerMgr.OnDraw();
        };


        //PageEvent 消息响应;
        this.OnPageVisable = function (pPageView, contentPanelWidth, contentPanelHeight, contentPanelOffset) {
            if (pPageView == null || !_bInited)
                return false;
            if (!_PageAnnotCreatedList[pPageView.GetPageIndex()]) {
                if (!pPageView.IsPageLoaded())
                    return false;
                var annotHtml =_pAnnotHandlerMgr.CreateAnnotsHtmlContent(pPageView);
                $("#" + pPageView.GetPageContainerID()).append(annotHtml);
                _PageAnnotCreatedList[pPageView.GetPageIndex()] = true;
            }

            var rcAnnotVisableRect = _pAnnotHandlerMgr.GetAnnotVisableRect(pPageView, contentPanelOffset, contentPanelWidth, contentPanelHeight);
            _self.UpdateAnnotsPosition(pPageView, rcAnnotVisableRect);
            _PageAnnotUpdatedList[pPageView.GetPageIndex()] = true;
            _pAnnotHandlerMgr.ShowAnnots(pPageView, true);
            return true;
        };

        this.OnPageShowComplete = function (pPageView) {
            if (pPageView == null || !_bInited)
                return false;
            if (pPageView.IsPageLoadError()) {
                return false;
            }
            if (_PageAnnotCreatedList[pPageView.GetPageIndex()] == null) {
                var annotHtml = _pAnnotHandlerMgr.CreateAnnotsHtmlContent(pPageView);
                $("#" + pPageView.GetPageContainerID()).append(annotHtml);
                _PageAnnotCreatedList[pPageView.GetPageIndex()] = true;
            }

            var jqPagesContainerDiv = $("#" + _pReaderApp.GetMainView().GetDocView().GetDocViewContainerID());
            var contentPanelHeight = jqPagesContainerDiv.height(); // $('#mainContainer').height();
            var contentPanelWidth = jqPagesContainerDiv.width();
            var contentPanelOffset = jqPagesContainerDiv.offset();
            this.OnPageVisable(pPageView, contentPanelWidth, contentPanelHeight, contentPanelOffset);

            return true;
        };

        this.OnPageInvisible = function (pPageView) {
        	_pAnnotHandlerMgr.ShowAnnots(pPageView, false);
            return true;
        };

        //重置Annot位置更新状态；
        this.ResetAnnotUpdatedList = function () {
            var iCnt = _pReaderApp.GetMainView().GetDocView().GetPDFDoc().GetPageCount();
            for (var i = 0; i < iCnt; i++) {
                _PageAnnotUpdatedList[i] = false;
            }
        };
        
        //更新Annot的位置;
        this.UpdateAnnotsPosition = function(pPageView, visableRect) {
            var pPDFPage = pPageView.GetPDFPage();
            var iAnnotCnt = pPDFPage.GetAnnotCount();
            for (var i = 0; i < iAnnotCnt; i++) {
                var annot = pPDFPage.GetAnnot(i);
                var annotPDFRect = null;
                var annotDocRect = null;
                if (_PageAnnotUpdatedList[pPageView.GetPageIndex()] == false) {
                    annotPDFRect = annot.GetRect();
                    annotDocRect = pPageView.PDF2Doc(annotPDFRect, true);
                    var annotDivID = _pAnnotHandlerMgr.GetAnnotDivID(pPageView, i);
                    $("#" + annotDivID).css({
                        left: annotDocRect.left,
                        top: annotDocRect.top,
                        width: FXREADER.RectUtils.Width(annotDocRect),
                        height: FXREADER.RectUtils.Height(annotDocRect)
                    });
                }
                if (annot.GetType() === "Markup") {
                	var subType = annot.GetSubType();
                	if((subType == FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_HIGHLIGHT
                			||subType == FXREADER.PDFData.CommentAnnotType.COMMENTTYPE_UNDERLINE)
                			&& _PageAnnotUpdatedList[pPageView.GetPageIndex()] == false)
                	{
                		var quadPoints = annot.GetQuadPoints();
                		var bUseQuad = false;
                		if(quadPoints != null)
                		{
                			var quadRectArray = _pAnnotHandlerMgr.QuadPointsToRectArray(quadPoints,subType);
                			if(quadRectArray != null)
                			{ 
                		          for (var j = 0; j < quadRectArray.length; j++) {
                		                var rect = quadRectArray[j];
                		                rect = pPageView.PDF2Doc(rect, true);
                		                var quadRectDivID = _pAnnotHandlerMgr.GetCommentAnnotQuadDivID(pPageView, i,j);
                		                $("#" + quadRectDivID).css({
                	                        left: rect.left,
                	                        top: rect.top,
                	                        width: FXREADER.RectUtils.Width(rect),
                	                        height: FXREADER.RectUtils.Height(rect)
                	                    });
                		          }
                		          bUseQuad = true;
                			}
                		}
                		if(!bUseQuad)
                		{
                			var rectDivId = _pAnnotHandlerMgr.GetCommentAnnotRectDivID(pPageView, i);
                			$("#" + rectDivId).css({
                                 left: annotDocRect.left,
                                 top: annotDocRect.top,
                                 width: FXREADER.RectUtils.Width(annotDocRect),
                                 height: FXREADER.RectUtils.Height(annotDocRect)
                            });
                		}
                	}
                    var popup = annot.GetPopup();
                    if (popup == null)
                        continue;
                    var popupDivID = _pAnnotHandlerMgr.GetAnnotPopupDivID(pPageView, i);
                    var popupPDFRect = popup.GetRect();
                    //注意参数bScale设为false
                    var popupDocRect = pPageView.PDF2Doc(popupPDFRect, false);
                    var width = FXREADER.RectUtils.Width(popupDocRect);
                    var height = FXREADER.RectUtils.Height(popupDocRect);
                    var visableWidth = FXREADER.RectUtils.Width(visableRect);
                    var visableHeight = FXREADER.RectUtils.Height(visableRect);
                    if (popupDocRect.top < visableRect.top) {
                        popupDocRect.top = visableRect.top;
                        popupDocRect.bottom = popupDocRect.top + height;
                    }

                    if (popupDocRect.bottom > visableRect.bottom) {
                        popupDocRect.bottom = visableRect.bottom;
                        popupDocRect.top = popupDocRect.bottom - height;
                    }
                    if (popupDocRect.left < visableRect.left) {
                        popupDocRect.left = visableRect.left;
                        popupDocRect.right = popupDocRect.left + width;
                    }
                    if (popupDocRect.right > visableRect.right) {
                        popupDocRect.right = visableRect.right;
                        if (popupDocRect.right - width > visableRect.left)
                            popupDocRect.left = popupDocRect.right - width;
                        if (popupDocRect.left >= popupDocRect.right)
                            popupDocRect.left = popupDocRect.right - width;
                        if (popupDocRect.left < visableRect.left)
                            popupDocRect.left = visableRect.left;
                    }


                    $("#" + popupDivID).css({
                        left: popupDocRect.left,
                        top: popupDocRect.top,
                        width: FXREADER.RectUtils.Width(popupDocRect),
                        height: FXREADER.RectUtils.Height(popupDocRect)
                    });
                }
            }
        };
        
        this.MovePopupAnnot = function (iPageIndex, iAnnotIndex, offsetX, offsetY) {
            var pDocView = _self.GetReaderApp().GetMainView().GetDocView();
            var pPageView = pDocView.GetPageView(iPageIndex);
            if (!pPageView)
                return false;
            var pPDFPage = pPageView.GetPDFPage();
            var annot = pPDFPage.GetAnnot(iAnnotIndex);
            if (!annot)
                return false;
            if (annot.GetType() != "Markup")
                return false;
            var popup = annot.GetPopup();
            if (popup == null)
                return false;
            var popupDivID = _pAnnotHandlerMgr.GetAnnotPopupDivID(pPageView, iAnnotIndex);
            var jqPopup = $("#" + popupDivID);
            var popupPDFRect = popup.GetRect();
            var nPt2Pixel = pDocView.GetPageViewRender().GetPixelsPerPoint();
            FXREADER.RectUtils.Offset(popupPDFRect,offsetX / pPageView.GetScale() / nPt2Pixel, -offsetY / pPageView.GetScale() / nPt2Pixel);
            popup.SetRect(popupPDFRect);
            var jqPagesContainerDiv = $("#" + pDocView.GetDocViewContainerID());
            var contentPaneHeight = jqPagesContainerDiv.height();
            var contentPanelWidth = jqPagesContainerDiv.width();
            var contentPanelOffset = jqPagesContainerDiv.offset();
            var rcAnnotVisableRect = _pAnnotHandlerMgr.GetAnnotVisableRect(pPageView, contentPanelOffset, contentPanelWidth, contentPaneHeight);
            _self.UpdateAnnotsPosition(pPageView, rcAnnotVisableRect);
        };
        
        //插件被注册的时候调用;
        this.PIOnRegister = function () {
        };

        //模块卸载;
        this.PIUnload = function () {
        };

        this.GetReaderApp = function () {
            return _pReaderApp;
        };
        
        this.RegisterAnnotHandler = function (pAnnotHandler)
        {
        	_pAnnotHandlerMgr.RegisterAnnotHandler(pAnnotHandler);
        };
        
        this.OnDraw = function()
        {
        	_pAnnotHandlerMgr.OnDraw();
        };
        
        this.GetHandlerManager = function()
        {
        	return _pAnnotHandlerMgr;
        };
	};

	exports.Reader_CreatePlugin = function (pReaderApp) {
        var pBaseAnnotPlugin = new FXREADER.CBaseAnnotPlugin(pReaderApp);
        return pBaseAnnotPlugin;
    };
});